package com.mooral.web.action.merchant;

import java.sql.ResultSet;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;

import com.mooral.bean.Bean;
import com.mooral.bean.Merchant;
import com.mooral.bean.Merchants;
import com.mooral.context.Context;
import com.mooral.web.action.MooralAction;

public class ViewAction extends MooralAction {

 	public ActionForward perform(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response, Context context) throws Exception {

		  DynaActionForm dform = (DynaActionForm) form;
		  String slug = (String)dform.get("query");
		  
		  Merchants merchants = new Merchants();
		  
			int pageSelected = 1;
			if (request.getParameter("pageSelected")!= null) {
				try{
					pageSelected = Integer.parseInt( request.getParameter("pageSelected") );
				}catch(NumberFormatException e){
					pageSelected = new Integer(1);
				}
			}		  
		  
		  
		  Bean bean = new Bean();

		  String sql = "select 	m.id as mid," +
			  		"						m.name as mname," +
			  		"						m.description as mdescription," +
			  		"						m.logo as mlogo," +
			  		"						v.id as vid," +
			  		"						v.title as vtitle," +
			  		"						v.image as vimage," +
			  		"						v.type as vtype," +
			  		"						v.description as vdescription," +
			  		"						v.slug as vslug" +
			  		"  			from 		merchants m " +
			  		"			left join 	vouchers v" +
			  		"				on 		(m.id = v.merchant_id)" +
			  		"			where 		m.slug = '" + slug + "'" +
			  		"			limit " + (pageSelected - 1) * Context.PAGE_SIZE + ", " + Context.PAGE_SIZE;
		  merchants.populate(bean, sql);

		  request.setAttribute("merchants", merchants);

		  
		  String name = merchants.get(0).get("mname").toString();
		  request.setAttribute("headerTitle", name + " Discount Codes | Vouchers &amp; Promotional Codes");
		  request.setAttribute("metaDescription", "Deals: " + name + " Discount codes, and " + name + " Voucher codes, coupons, offers and promos." + name + " promotional codes");
		  request.setAttribute("metaKeywords", name + ", voucher codes, discount codes, " + name + " coupon codes, " + name + " discount voucher, discounts, discount code, coupons, " + name + " promo, promotional codes, checkout codes, online discount");
		  
		  if(merchants.get(0).get("vid") != null)
			  request.setAttribute("merchantHaveVouchers", true);
		  

			// Paginacion
			request.setAttribute("listSize", merchants.getCount(sql));
			request.setAttribute("actionSearch", mapping.getPath());
			request.setAttribute("query", slug);
			request.setAttribute("pageSelected", new Integer(pageSelected));
		  

		  return mapping.findForward(ACTION_SUCCESS);
	}
	
}
